/**
 * Copyright 2009-2019 the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.ibatis.builder.xml;

import org.apache.ibatis.builder.BaseBuilder;
import org.apache.ibatis.builder.BuilderException;
import org.apache.ibatis.datasource.DataSourceFactory;
import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.loader.ProxyFactory;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.io.VFS;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.mapping.DatabaseIdProvider;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaClass;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.AutoMappingBehavior;
import org.apache.ibatis.session.AutoMappingUnknownColumnBehavior;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.LocalCacheScope;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.type.JdbcType;

import javax.sql.DataSource;
import java.io.InputStream;
import java.io.Reader;
import java.util.Properties;

/**
 * @author Clinton Begin
 * @author Kazuki Shimizu
 */
public class XMLConfigBuilder extends BaseBuilder {

    /**
     * 解析标识。mybatis-config是全局唯一的，因此解析一次就够了
     * true标识已经解析过
     */
    private boolean parsed;

    /**
     * XML解析器
     */
    private final XPathParser parser;

    /**
     * 当前环境
     */
    private String environment;
    private final ReflectorFactory localReflectorFactory = new DefaultReflectorFactory();

    public XMLConfigBuilder(Reader reader) {
        this(reader, null, null);
    }

    public XMLConfigBuilder(Reader reader, String environment) {
        this(reader, environment, null);
    }

    public XMLConfigBuilder(Reader reader, String environment, Properties props) {
        this(new XPathParser(reader, true, props, new XMLMapperEntityResolver()), environment, props);
    }

    public XMLConfigBuilder(InputStream inputStream) {
        this(inputStream, null, null);
    }

    public XMLConfigBuilder(InputStream inputStream, String environment) {
        this(inputStream, environment, null);
    }

    public XMLConfigBuilder(InputStream inputStream, String environment, Properties props) {
        this(new XPathParser(inputStream, true, props, new XMLMapperEntityResolver()), environment, props);
    }

    private XMLConfigBuilder(XPathParser parser, String environment, Properties props) {
        super(new Configuration());
        ErrorContext.instance().resource("SQL Mapper Configuration");
        this.configuration.setVariables(props);
        this.parsed = false;
        this.environment = environment;
        this.parser = parser;
    }

    public Configuration parse() {
        if (parsed) {
            // 已经解析过就不再解析。这里只解析一次
            throw new BuilderException("每个 XMLConfigBuilder 只能使用一次.");
        }
        parsed = true;
        // 获取configuration节点进行解析
        parseConfiguration(parser.evalNode("/configuration"));
        return configuration;
    }

    /**
     * 解析mybatis-config.xml文件
     *
     * @param root
     */
    private void parseConfiguration(XNode root) {
        try {
            // 解析properties节点。该节点用来引入外部的资源文件，如db.properties
            propertiesElement(root.evalNode("properties"));
            // 解析settings节点，校验配置中的配置项是否合法。该节点用来设置一些mybatis的配置项
            Properties settings = settingsAsProperties(root.evalNode("settings"));
            // 加载用户自己配置的虚拟文件系统
            loadCustomVfs(settings);
            // 加载日志
            loadCustomLogImpl(settings);
            // 解析typeAliases节点
            typeAliasesElement(root.evalNode("typeAliases"));
            // 解析plugins节点
            pluginElement(root.evalNode("plugins"));
            // 解析objectFactory节点
            objectFactoryElement(root.evalNode("objectFactory"));
            // 解析objectWrapperFactory节点
            objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
            // 解析reflectorFactory节点
            reflectorFactoryElement(root.evalNode("reflectorFactory"));
            // 将settings节点的配置set到Configuration中
            settingsElement(settings);
            // 解析environments节点
            environmentsElement(root.evalNode("environments"));
            // 解析databaseIdProvider节点
            databaseIdProviderElement(root.evalNode("databaseIdProvider"));
            // 解析typeHandler节点
            typeHandlerElement(root.evalNode("typeHandlers"));
            // 解析mappers节点
            mapperElement(root.evalNode("mappers"));
        } catch (Exception e) {
            throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
        }
    }

    /**
     * 解析settings节点
     *
     * @param context
     * @return
     */
    private Properties settingsAsProperties(XNode context) {
        if (context == null) {
            return new Properties();
        }
        // 获取settings节点下所有的setting节点
        Properties props = context.getChildrenAsProperties();
        // 通过Configuration获取metaClass，用于方便对Configuration进行操作
        MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
        for (Object key : props.keySet()) {
            // 遍历setting配置
            // 如果Configuration没有这个set方法，说明该配置是无效的
            if (!metaConfig.hasSetter(String.valueOf(key))) {
                throw new BuilderException("配置 " + key + " 无效. 请检查拼写是否正确.");
            }
        }
        // 校验完settings之后返回
        return props;
    }

    /**
     * 加载用户自己设置的虚拟文件系统
     *
     * @param props
     * @throws ClassNotFoundException
     */
    private void loadCustomVfs(Properties props) throws ClassNotFoundException {
        // 从settings中拿到name是vfsImpl的配置节点
        String value = props.getProperty("vfsImpl");
        if (value != null) {
            String[] clazzes = value.split(",");
            for (String clazz : clazzes) {
                if (!clazz.isEmpty()) {
                    @SuppressWarnings("unchecked")
                    Class<? extends VFS> vfsImpl = (Class<? extends VFS>) Resources.classForName(clazz);
                    // 加载文件系统，set到Configuration中
                    configuration.setVfsImpl(vfsImpl);
                }
            }
        }
    }

    /**
     * 加载日志。代码比较简单
     * 就是从settings中拿到name为logImpl的配置项
     * 然后set到Configuration中去
     *
     * @param props
     */
    private void loadCustomLogImpl(Properties props) {
        Class<? extends Log> logImpl = resolveClass(props.getProperty("logImpl"));
        configuration.setLogImpl(logImpl);
    }

    /**
     * 解析typeAliases节点
     *
     * @param parent
     */
    private void typeAliasesElement(XNode parent) {
        if (parent != null) {
            // 遍历所有子节点
            // typeAliases节点有两个子节点，分别是package和typeAlias
            for (XNode child : parent.getChildren()) {
                if ("package".equals(child.getName())) {
                    // 获取name属性，package的name属性指定的是包名
                    String typeAliasPackage = child.getStringAttribute("name");
                    // 将这个包下的所有类注册别名
                    configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
                } else {
                    // 如果配置的是typeAlias节点，就将该节点的类单独注册
                    String alias = child.getStringAttribute("alias");
                    String type = child.getStringAttribute("type");
                    try {
                        Class<?> clazz = Resources.classForName(type);
                        if (alias == null) {
                            typeAliasRegistry.registerAlias(clazz);
                        } else {
                            typeAliasRegistry.registerAlias(alias, clazz);
                        }
                    } catch (ClassNotFoundException e) {
                        throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
                    }
                }
            }
        }
    }

    /**
     * 解析plugins节点
     * plugin节点用于配置插件
     * 即 mybatis拦截器
     *
     * @param parent
     * @throws Exception
     */
    private void pluginElement(XNode parent) throws Exception {
        if (parent != null) {
            // 获取子节点，子节点就是所配置的拦截器
            for (XNode child : parent.getChildren()) {
                // 获得拦截器全类名
                String interceptor = child.getStringAttribute("interceptor");
                // 将节点下的节点封装成properties
                Properties properties = child.getChildrenAsProperties();
                // 根据拦截器的全类名，通过默认构造方法创建一个实例
                Interceptor interceptorInstance = (Interceptor) resolveClass(interceptor).getDeclaredConstructor().newInstance();
                // 将拦截器节点下的properties放到拦截器中
                interceptorInstance.setProperties(properties);
                // 将拦截器添加到配置中
                configuration.addInterceptor(interceptorInstance);
            }
        }
    }

    /**
     * 解析objectFactory节点
     * objectFactory用来处理查询得到的结果集
     * 创建对象去将结果集封装到对象中
     * mybatis默认的object工厂是用无参构造或者有参构造去创建对象
     * 而如果开发者想在创建对象前对其中的一些属性做初始化操作
     * 或者做一些业务方面的逻辑
     * 就可以自己去创建对象工厂并进行配置
     *
     * @param context
     * @throws Exception
     */
    private void objectFactoryElement(XNode context) throws Exception {
        if (context != null) {
            // 拿到objectFactory节点的type属性，该属性为对象工厂的全类名
            String type = context.getStringAttribute("type");
            // 拿到节点下所有的properties
            Properties properties = context.getChildrenAsProperties();
            // 根据type对应的类，通过默认构造去创建一个实例
            ObjectFactory factory = (ObjectFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            // 将properties放入对象工厂
            factory.setProperties(properties);
            // 将对象工厂添加到配置中去
            configuration.setObjectFactory(factory);
        }
    }

    /**
     * 解析objectWrapperFactory节点
     *
     * @param context
     * @throws Exception
     */
    private void objectWrapperFactoryElement(XNode context) throws Exception {
        if (context != null) {
            // 获取到type属性
            String type = context.getStringAttribute("type");
            // 根据type属性对应的类去创建对象
            ObjectWrapperFactory factory = (ObjectWrapperFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            // 将对象放到配置中
            configuration.setObjectWrapperFactory(factory);
        }
    }

    /**
     * 解析reflectorFactory节点。代码比较简单就不写了。
     * 解析流程和objectWrapperFactory一毛一样
     *
     * @param context
     * @throws Exception
     */
    private void reflectorFactoryElement(XNode context) throws Exception {
        if (context != null) {
            String type = context.getStringAttribute("type");
            ReflectorFactory factory = (ReflectorFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            configuration.setReflectorFactory(factory);
        }
    }

    /**
     * 解析mybatis-config.xml的properties节点
     * 将节点中所有的配置set到Configuration中
     *
     * @param context
     * @throws Exception
     */
    private void propertiesElement(XNode context) throws Exception {
        if (context != null) {
            // 解析拿到节点下的所有子节点配置
            Properties defaults = context.getChildrenAsProperties();
            // 获取properties节点的resource属性
            String resource = context.getStringAttribute("resource");
            // 获取properties节点的url属性。
            String url = context.getStringAttribute("url");
            if (resource != null && url != null) {
                // resource和url属性只能同时存在一个。
                throw new BuilderException("properties节点不能同时指定resource和url两个属性.");
            }
            // url和resource属性只能同时存在一个
            // 读取引入的资源文件所有属性，put到properties节点之下
            if (resource != null) {
                defaults.putAll(Resources.getResourceAsProperties(resource));
            } else if (url != null) {
                defaults.putAll(Resources.getUrlAsProperties(url));
            }
            Properties vars = configuration.getVariables();
            // 如果configuration之前已经有了配置，也put进去
            // put这些设置是为了能够保证后面set回configuration时可以set所有的配置
            if (vars != null) {
                defaults.putAll(vars);
            }
            parser.setVariables(defaults);
            // 将Properties节点下所有的配置set到configuration
            configuration.setVariables(defaults);
        }
    }

    /**
     * 将settings节点的配置set到Configuration中
     *
     * @param props
     */
    private void settingsElement(Properties props) {
        configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
        configuration.setAutoMappingUnknownColumnBehavior(AutoMappingUnknownColumnBehavior.valueOf(props.getProperty("autoMappingUnknownColumnBehavior", "NONE")));
        configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
        configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
        configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
        configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), false));
        configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
        configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
        configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
        configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
        configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
        configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
        configuration.setDefaultResultSetType(resolveResultSetType(props.getProperty("defaultResultSetType")));
        configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
        configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
        configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
        configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
        configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
        configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
        configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
        configuration.setDefaultEnumTypeHandler(resolveClass(props.getProperty("defaultEnumTypeHandler")));
        configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
        configuration.setUseActualParamName(booleanValueOf(props.getProperty("useActualParamName"), true));
        configuration.setReturnInstanceForEmptyRow(booleanValueOf(props.getProperty("returnInstanceForEmptyRow"), false));
        configuration.setLogPrefix(props.getProperty("logPrefix"));
        configuration.setConfigurationFactory(resolveClass(props.getProperty("configurationFactory")));
    }

    /**
     * 解析environments节点
     * 该节点表示环境配置
     * 所谓环境，就是指运行时环境，即开发环境、测试环境、生产环境
     * 环境最直观的提现就是在不同环境下数据库不同
     * environments节点下就提供了数据源和事务配置
     *
     * @param context
     * @throws Exception
     */
    private void environmentsElement(XNode context) throws Exception {
        if (context != null) {
            if (environment == null) {
                // 获取默认的环境id
                environment = context.getStringAttribute("default");
            }
            for (XNode child : context.getChildren()) {
                // 拿到子节点的id。父节点的default属性对应的就是子节点id
                String id = child.getStringAttribute("id");
                if (isSpecifiedEnvironment(id)) {
                    // 解析事务管理器
                    TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
                    // 解析数据工厂
                    DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
                    // 从工厂中拿到数据库
                    DataSource dataSource = dsFactory.getDataSource();
                    // 创建环境并set到Configuration中去
                    Environment.Builder environmentBuilder = new Environment.Builder(id)
                            .transactionFactory(txFactory)
                            .dataSource(dataSource);
                    configuration.setEnvironment(environmentBuilder.build());
                }
            }
        }
    }

    /**
     * 解析databaseIdProvider节点
     * 该节点用于提供多数据源支持
     * 这里的多数据源并非指多个数据库
     * 而是指多个数据库产品
     * 这里的代码和objectFactory类似
     *
     * @param context
     * @throws Exception
     */
    private void databaseIdProviderElement(XNode context) throws Exception {
        DatabaseIdProvider databaseIdProvider = null;
        if (context != null) {
            String type = context.getStringAttribute("type");
            // awful patch to keep backward compatibility
            if ("VENDOR".equals(type)) {
                type = "DB_VENDOR";
            }
            Properties properties = context.getChildrenAsProperties();
            databaseIdProvider = (DatabaseIdProvider) resolveClass(type).getDeclaredConstructor().newInstance();
            databaseIdProvider.setProperties(properties);
        }
        // 获取当前环境
        Environment environment = configuration.getEnvironment();
        if (environment != null && databaseIdProvider != null) {
            String databaseId = databaseIdProvider.getDatabaseId(environment.getDataSource());
            configuration.setDatabaseId(databaseId);
        }
    }

    /**
     * 解析事务管理器配置
     * 解析步骤和objectFactory一样
     *
     * @param context
     * @return
     * @throws Exception
     */
    private TransactionFactory transactionManagerElement(XNode context) throws Exception {
        if (context != null) {
            String type = context.getStringAttribute("type");
            Properties props = context.getChildrenAsProperties();
            TransactionFactory factory = (TransactionFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            factory.setProperties(props);
            return factory;
        }
        throw new BuilderException("Environment declaration requires a TransactionFactory.");
    }

    /**
     * 解析数据源工厂
     *
     * @param context
     * @return
     * @throws Exception
     */
    private DataSourceFactory dataSourceElement(XNode context) throws Exception {
        if (context != null) {
            String type = context.getStringAttribute("type");
            Properties props = context.getChildrenAsProperties();
            DataSourceFactory factory = (DataSourceFactory) resolveClass(type).getDeclaredConstructor().newInstance();
            factory.setProperties(props);
            return factory;
        }
        throw new BuilderException("Environment declaration requires a DataSourceFactory.");
    }

    /**
     * 解析typeHandlers节点
     * 该节点用于将指定的数据库类型转换成java类型
     * 该节点有typeHandler和package两个子节点
     * 自定义的typeHandler需要实现TypeHandler接口
     *
     * @param parent
     */
    private void typeHandlerElement(XNode parent) {
        if (parent != null) {
            for (XNode child : parent.getChildren()) {
                if ("package".equals(child.getName())) {
                    String typeHandlerPackage = child.getStringAttribute("name");
                    typeHandlerRegistry.register(typeHandlerPackage);
                } else {
                    // 获取到typeHandler节点的三个属性，并获取到对应的类型
                    String javaTypeName = child.getStringAttribute("javaType");
                    String jdbcTypeName = child.getStringAttribute("jdbcType");
                    String handlerTypeName = child.getStringAttribute("handler");
                    Class<?> javaTypeClass = resolveClass(javaTypeName);
                    JdbcType jdbcType = resolveJdbcType(jdbcTypeName);
                    Class<?> typeHandlerClass = resolveClass(handlerTypeName);
                    // 注册类型处理器
                    if (javaTypeClass != null) {
                        if (jdbcType == null) {
                            typeHandlerRegistry.register(javaTypeClass, typeHandlerClass);
                        } else {
                            typeHandlerRegistry.register(javaTypeClass, jdbcType, typeHandlerClass);
                        }
                    } else {
                        // java类为空，调用register。这个方法内部会判断类型处理器上是否有MappedTypes注解
                        typeHandlerRegistry.register(typeHandlerClass);
                    }
                }
            }
        }
    }

    /**
     * 解析mappers节点。该节点作用是扫描xml
     * 并将扫描到的xml进行解析
     * 该节点提供了package和mapper两种配置方式
     *
     * @param parent
     * @throws Exception
     */
    private void mapperElement(XNode parent) throws Exception {
        if (parent != null) {
            for (XNode child : parent.getChildren()) {
                if ("package".equals(child.getName())) {
                    String mapperPackage = child.getStringAttribute("name");
                    // 扫描指定的包，并向MapperRegistry注册Mapper接口
                    configuration.addMappers(mapperPackage);
                } else {
                    // 获取到resource属性，resource属性指定mapper.xml
                    String resource = child.getStringAttribute("resource");
                    // url，这是个没什么卵用的属性。
                    String url = child.getStringAttribute("url");
                    // 指定class
                    String mapperClass = child.getStringAttribute("class");
                    // 只有resource
                    if (resource != null && url == null && mapperClass == null) {
                        // 将mapper文件路径放到error上下文
                        ErrorContext.instance().resource(resource);
                        // 通过流去获取映射文件
                        InputStream inputStream = Resources.getResourceAsStream(resource);
                        // 创建XMLMapperBuilder对象，即系映射配置文件
                        XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
                        mapperParser.parse();
                    } else if (resource == null && url != null && mapperClass == null) {
                        // 只有url
                        ErrorContext.instance().resource(url);
                        InputStream inputStream = Resources.getUrlAsStream(url);
                        XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
                        mapperParser.parse();
                    } else if (resource == null && url == null && mapperClass != null) {
                        // 只有mapperClass
                        Class<?> mapperInterface = Resources.classForName(mapperClass);
                        // 如果mapper节点制定了class属性
                        configuration.addMapper(mapperInterface);
                    } else {
                        // 这三个属性是互斥的，所以不能同时存在其中任意两个以上
                        throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
                    }
                }
            }
        }
    }

    /**
     * 判断是否是该环境
     *
     * @param id
     * @return
     */
    private boolean isSpecifiedEnvironment(String id) {
        if (environment == null) {
            throw new BuilderException("No environment specified.");
        } else if (id == null) {
            throw new BuilderException("Environment requires an id attribute.");
        } else if (environment.equals(id)) {
            return true;
        }
        return false;
    }

}
